﻿namespace PlanckSys.Jira.RssJiraRedirector
{
    #region Imports
    using ConfigurationManager = System.Configuration.ConfigurationManager;
    using EventLog = System.Diagnostics.EventLog;
    using Exception = System.Exception;
    using RouteParameter = System.Web.Http.RouteParameter;
    using HttpSelfHostConfiguration = System.Web.Http.SelfHost.HttpSelfHostConfiguration;
    using HttpSelfHostServer = System.Web.Http.SelfHost.HttpSelfHostServer;
    #endregion

    public partial class RssJiraRedirectorService : System.ServiceProcess.ServiceBase
    {

        public static readonly string JOB_DATA_MAP_KEY_EVENT_LOG = "eventLog1";
        protected internal static void RunService()
        {
            System.ServiceProcess.ServiceBase[] ServicesToRun;
            ServicesToRun = new System.ServiceProcess.ServiceBase[]
                    {
                        new RssJiraRedirectorService ( )
                    };
            System.ServiceProcess.ServiceBase.Run(ServicesToRun);
        }
        protected internal static void RunConsole()
        {

            using (RssJiraRedirectorService consoleService = new RssJiraRedirectorService())
            {

                consoleService.OnStart(null);

                System.Windows.Forms.MessageBox.Show("Click ok button to end service");
                //// Wait for the user to quit the program.


            }

        }
        public RssJiraRedirectorService()
        {
            try
            {
                InitializeComponent();
                //To create the source, you need permission to read all event logs to make sure
                //that the new source name is unique.  Inaccessible logs: Security.
                //If you use the sourceName of the Service you added the event log to then you dont have to create
                string SourceName = "RssJiraRedirectorService";
                string logName = "Application";
                try
                {
                    if (!System.Diagnostics.EventLog.SourceExists(SourceName))
                    {
                        EventLog.CreateEventSource(SourceName, logName);
                    }
                }
                catch (Exception eIgnore)
                {
                    try
                    {
                        //we are not looking in security logs so ignore
                        EventLog.CreateEventSource(SourceName, logName);
                    }
                    catch (Exception eIgnore1)
                    {
                        throw;
                    }
                }
                eventLog1 = new EventLog();
                eventLog1.Source = SourceName;

                //bug possible cant change listening address without service reboot.
                HttpSelfHostConfiguration config = new HttpSelfHostConfiguration(ConfigurationManager.AppSettings["SchedulerHostBaseAddress"]);
                config.HostNameComparisonMode = System.ServiceModel.HostNameComparisonMode.WeakWildcard;
                System.Collections.Generic.IDictionary<string, object> data = new System.Collections.Generic.Dictionary<string, object>();
                data.Add("id", RouteParameter.Optional);
                System.Web.Http.HttpRouteCollectionExtensions.MapHttpRoute(config.Routes, "default", "{controller}/{id}", data);


                //config.Routes.MapHttpRoute("default", "{controller}/{id}", new { id = RouteParameter.Optional });
                _server = new HttpSelfHostServer(config);
            }
            catch (Exception e)
            {
                if (eventLog1 != null)
                {
                    string message = string.Format("error {0}, Exception: {1} \n\nStack: {2}", "Log", e.Message, e.StackTrace);
                    eventLog1.WriteEntry(message, System.Diagnostics.EventLogEntryType.Error);
                }
                throw;
            }
        }

        protected override void OnStart(string[] args)
        {

            try
            {
                if (_server != null)
                {
                    _server.OpenAsync().Wait();
                }


            }
            catch (Exception e)
            {
                if (eventLog1 != null)
                {
                    string message = string.Format("error {0}, Exception: {1} \n\nStack: {2}", "Log", e.Message, e.StackTrace);
                    eventLog1.WriteEntry(message, System.Diagnostics.EventLogEntryType.Error);
                }
                throw;

            }

        }

        protected override void OnStop()
        {
            try
            {
                _server.CloseAsync().Wait();
                _server = null;
            }
            catch (Exception e)
            {
                if (eventLog1 != null)
                {
                    string message = string.Format("error {0}, Exception: {1} \n\nStack: {2}", "Log", e.Message, e.StackTrace);
                    eventLog1.WriteEntry(message, System.Diagnostics.EventLogEntryType.Error);
                }
                throw;

            }

        }
    }
}
